﻿using System.Collections.Generic;
using UnityEngine;

namespace GameToolkit
{
    [RequireComponent(typeof(ActorBehaviour)), DisallowMultipleComponent]
    public class LocalPlayerController : MonoBehaviour, ActorBehaviour.IController
    {
        [SerializeField]
        int m_Priority;

        [SerializeField, Range(2, 16)]
        int m_InitInputCapacity = 4;

        ActorBehaviour mActor;
        Dictionary<Object, ActorBehaviour.IInputAction> mCloneDescriptors;

        public ActorBehaviour Actor => mActor;
        int ActorBehaviour.IController.Priority => m_Priority;

        ActorBehaviour.IInputAction ActorBehaviour.IController.GetInputAction(Object descriptor)
        {
            if (mCloneDescriptors == null)
                return null;
            ActorBehaviour.IInputAction act;
            if (!mCloneDescriptors.TryGetValue(descriptor, out act) && descriptor is InputDescriptor desc)
            {
                act = desc.Create(true);
                if (act != null)
                {
                    mCloneDescriptors[desc] = act;
                }
            }
            return act;
        }

        public virtual void OnActivate()
        {
        }

        public virtual void OnControlling(float deltaTime)
        {
        }

        public virtual void OnDeactivate()
        {
        }

        public virtual void OnFeatureDisable(ActorBehaviour actor)
        {
        }

        public virtual void OnFeatureEnable(ActorBehaviour actor)
        {
            mActor = actor;
            if (mCloneDescriptors == null)
            {
                mCloneDescriptors = new Dictionary<Object, ActorBehaviour.IInputAction>(m_InitInputCapacity);
            }
        }

        protected virtual void OnDestroy()
        {
            if (mCloneDescriptors != null)
            {
                foreach (var desc in mCloneDescriptors.Values)
                {
                    if (desc is System.IDisposable dispose)
                        dispose.Dispose();
                }
                mCloneDescriptors.Clear();
                mCloneDescriptors = null;
            }
        }
    }
}
